from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.utils import decode_sign_openid

from oauth.models import OAuthQQUser

from users.models import User


class UersSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=20,min_length=8,label="密码")
    mobile = serializers.RegexField(regex=r'^1[3-9]\d{9}$',label="手机号码")
    sms_code = serializers.CharField(max_length=6,min_length=6,label="短信验证码")
    access_token = serializers.CharField(label="加密的openid")

    def validate(self, attrs):
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        #对短信验证码进行校验
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        #校验有没有这个用户
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            raise serializers.ValidationError("该用户不存在")
        else:
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("输入密码有误")

        #对openid进行校验
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError("openid有误")

        attrs["openid"] = openid
        attrs["user"] = user

        return attrs
        pass
    pass

    def create(self, validated_data):

        #创建数据
        openid = validated_data["openid"]
        user = validated_data["user"]

        #如果没有user,则创建一个
        if not user:
            user = User.objects.create_user(
                username=validated_data["mobile"],
                password=validated_data["password"],
                mobile=validated_data["mobile"]
            )
        #创建OAuthQQUser对象
        OAuthQQUser.objects.create(openid=openid,user_id=user.id)

        return user
        pass

"""
        #使用access_token获取用户对象,然后对密码进行校验
        access_token = attrs["access_token"]
        openid_b = access_token.encode()
        openid_s = decode_sign_openid(openid_b)????????为什么不需要编码.

        qq_user = OAuthQQUser.objects.get(openid = openid_s)
        user = qq_user.user
        if not user.check_password(attrs["password"]):
            raise serializers.ValidationError("密码错误")
"""

